﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LuckyLoot.ServiceFacade.Implementation;
using LuckyLoot.ServiceFacade.Contracts;
using LuckyLoot.Presentation.BasePage;
using LuckyLoot.Common.Validation;
using LuckyLoot.Domain.Entities.People;

namespace LuckyLoot.Presentation
{
    public partial class SupplierPage : LuckyLootPage
    {
        private const string QueryStringSupplierID = "SupplierID";

        private ISupplierManagementService _supplierService;
        public ISupplierManagementService SupplierService
        {
            get
            {
                if (_supplierService == null)
                    _supplierService = new SupplierManagementService();

                return _supplierService;
            }
        }

        public int SupplierID
        {
            set
            {
                this.ViewState[QueryStringSupplierID] = value;
            }
            get
            {
                int viewStateTypedSupplierID;

                if (this.ViewState[QueryStringSupplierID] != null)
                {
                    if (Int32.TryParse(this.ViewState[QueryStringSupplierID].ToString(), out viewStateTypedSupplierID))
                        return viewStateTypedSupplierID;
                }

                return 0;
            }
        }

        public bool HasSelectedRecord
        {
            get
            {
                return SupplierID > 0;
            }
        }

        private void SetCommandsVisibility()
        {

        }

        private void SelectRecord(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                int intID;
                if (Int32.TryParse(id, out intID))
                    SelectRecord(intID);
            }

        }

        private void SelectRecord(int id)
        {
            ValidState.Requires<ArgumentException>(id > 0);
            var supplier = this.SupplierService.GetSupplier(id);

            SelectRecord(supplier);
        }

        private void SelectRecord(LuckyLoot.Domain.Entities.People.Supplier supplier)
        {
            this.supplierName.Text = supplier.Name;
            this.supplierPhone.Text = supplier.Phone;
            this.supplierEmail.Text = supplier.Email;
            this.supplierDescription.Text = supplier.ServiceDescription;
            this.supplierWebSite.Text = supplier.WebSite;
            this.supplierLatestPurchase.Text = supplier.LatestPurchase.ToString();

            this.SupplierID = supplier.Id;
        }

        private void ClearRecordSelection()
        {
            this.SupplierID = 0;
            this.ClearFields();
        }

        private void ClearFields()
        {
            this.supplierName.Text = string.Empty;
            this.supplierPhone.Text = string.Empty;
            this.supplierEmail.Text = string.Empty;
            this.supplierDescription.Text = string.Empty;
            this.supplierWebSite.Text = string.Empty;
            this.supplierLatestPurchase.Text = string.Empty;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    var supplierIDString = HttpContext.Current.Request.QueryString[QueryStringSupplierID];
                    this.SelectRecord(supplierIDString);
                }

                this.SaveSupplier.Click += new EventHandler(SaveSupplierClick);
                this.SetCommandsVisibility();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                MasterPage.ShowErrorMessage(ex.Message);
            }
        }

        public void SaveSupplierClick(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(supplierName.Text))
                throw new ArgumentNullException("supplierName", "É obrigatório informar o nome do fornecedor.");

            DateTime lastPurchase;
            if (!DateTime.TryParse(supplierLatestPurchase.Text, out lastPurchase))
                throw new ArgumentException("Não foi possível converter em uma Data o valor informado no campo Data da última compra.");

            Supplier supplier;
            if (this.HasSelectedRecord)
                supplier = this.SupplierService.UpdateSupplier(SupplierID, supplierName.Text, supplierPhone.Text, supplierEmail.Text, supplierDescription.Text, supplierWebSite.Text, lastPurchase);
            else
                supplier = this.SupplierService.CreateSupplier(supplierName.Text, supplierPhone.Text, supplierEmail.Text, supplierDescription.Text, supplierWebSite.Text, lastPurchase);

            this.SelectRecord(supplier);
            this.SetCommandsVisibility();
            MasterPage.ShowSuccessMessage("Fornecedor salvo com sucesso!");
            this.BindGrid();
        }

        private void BindGrid()
        {
            var suppliers = this.SupplierService.GetAllSuppliers();

            if (suppliers.Count() > 0)
            {
                this.suppliersGrid.DataSource = suppliers;
                this.suppliersGrid.DataBind();
                this.suppliersGrid.Visible = true;
                this.suppliersLabel.Visible = true;
            }
        }
    }
}